//
//  CurrencyExchangeViewController.swift
//  Exchange
//
//  Created by rui on 2018/4/18.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class CurrencyExchangeViewController: BaseViewController, DSWebSocketDelegate, SocketManagerDelegate {
    lazy var viewModel:CurrencyExchangeViewModel = {
       let viewModel = CurrencyExchangeViewModel(controller:self)
        return viewModel
    }()
    lazy var currencyView:CurrencyExchangeView = {
       let view = CurrencyExchangeView(dataSource: viewModel)
        return view 
    }()
    var sideslipView:SideslipView?
    lazy var leftBtn:CustomBtn = {
        let btn = CustomBtn(style: placeStyle.styleRight)
        btn.photoImageView.image = UIImage(named: "retractLeft")
        btn.photoImageView.themeImage = ThemeManager.ThemeImageKeys.coinRetract
        btn.nameLabel.themeTextColor = ThemeManager.ThemeColorKeys.text1
        btn.addTarget(self, action: #selector(leftBtnAction), for: UIControlEvents.touchUpInside)
        btn.nameLabel.font = UIFont(name: "PingFang-SC-Bold", size: 14)
        btn.bounds = CGRect(x: 0, y: 0, width:100, height: 44)
        return btn
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "goto_chart"), style: .plain, target: self, action: #selector(goKline))

        // Do any additional setup after loading the view.
        view.addSubview(currencyView)
        currencyView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-49)
        }
        self.creatLeftItem()
        
        if !APPTransactionPair.default.isRequestFail {
            self.viewModel.selectPairName = APPTransactionPair.default.archiveTitleArray().count > 0 ? APPTransactionPair.default.archiveTitleArray().first! : ""
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.defaultTheme()
        self.setStatusBarStyle()
        currencyView.controller = nil
        
        //判断是否设置交易密码 没有设置请求
        if !AppSecurityInfo.default.model.isTradePwd {
            AppSecurityInfo.default.archiveSecurityInfo()
        }
        currencyView.numberView.textField.setPlaceholderColor()
        
        //如果登录 订阅当前委托推送
        if AppInfo.default.isLogin {
            //获取币币资产
            self.viewModel.archiveInformation()
            self.archiveOrderDepth()
        }
        //网络请求结束 没有失败
        APPTransactionPair.default.delegate = self
        SocketManager.shared.delegate = self
        if APPTransactionPair.default.isRequestIng == false &&  !APPTransactionPair.default.isRequestFail {
            viewModel.currentPairModel = APPTransactionPair.default.selectPairModel
            //订阅深度
            viewModel.isRefreshDepth = true
            //订阅交易对
            self.viewModel.isRefreshPair = true
            //匹配当前委托单
            viewModel.currentOder = CoinOrderModel()
            viewModel.checkUpdateModel()
            
            self.viewModel.changePair = true
            viewModel.digit = String(format: "%d", self.viewModel.regularModel.priceDigit)
            currencyView.digitBtn.nameLabel.text = kText("小数位数") + (viewModel.digit)!
            currencyView.digitBtn.isHidden = false
            self.changeLeftName()
        }else {
            self.leftBtn.nameLabel.text = kText("暂无交易对")
        }
        //网络请求结束 并且 请求失败
        if APPTransactionPair.default.isRequestIng == false && APPTransactionPair.default.isRequestFail {
            APPTransactionPair.default.startPair()
        }
        
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if currencyView.controller == nil {
             if AppInfo.default.isLogin {
                viewModel.coinOrderArr.removeAll()
                currencyView.entrustTableView.reloadData()
                ServiceSocketManager.shared.isLeave = true
                ServiceSocketManager.shared.closeSocket()
             }
        }
        viewModel.selectPrice = ""
        self.viewModel.isRefreshDepth = false
        self.viewModel.isRefreshPair = false
    }
    func creatLeftItem() -> Void {
        leftBtn.frame = CGRect(x: 0, y: 0, width:100, height: 44)
        let item  = UIBarButtonItem(customView: leftBtn)
        leftBtn.photoImageView.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        leftBtn.nameLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalTo(leftBtn.photoImageView.snp.right).offset(5)
        }
        self.navigationItem.leftBarButtonItem = item
        if #available(iOS 11, *) {
        leftBtn.snp.remakeConstraints { (make) in
            make.left.equalTo(item.customView!)
            make.top.equalTo(item.customView!)
            make.height.equalTo(44)
            make.width.equalTo(100)
        }
        leftBtn.setNeedsLayout()
        leftBtn.layoutIfNeeded()
        }
        
    }
    
    func changeLeftName()  {
        if  viewModel.isPairBool {
            self.leftBtn.nameLabel.text =  viewModel.currentPairModel.name
            self.leftBtn.nameLabel.changeLabelTextStyle(title: viewModel.sourceCoin, color: (self.leftBtn.nameLabel.textColor)!, font: UIFont(name: "PingFang-SC-Medium", size: 11)!)
        }else {
            self.leftBtn.nameLabel.text = kText("暂无交易对")
        }
    }
    
    @objc func leftBtnAction() -> Void {
        self.view.endEditing(true)
        
        if sideslipView == nil {
            sideslipView = SideslipView()
        }
        ///取消订阅
        viewModel.isRefreshPair = false
        sideslipView?.isHidden = false
        sideslipView?.currentPairModel = viewModel.currentPairModel
        sideslipView?.startSubscription()
        sideslipView!.showSides()
        sideslipView?.tableView.reloadData()
        
        sideslipView?.sideslipBlock = {[weak self] model in
            if model.name != self?.viewModel.currentPairModel.name {
                self?.viewModel.isRemoveDepthData = true
                self?.currencyView.tableView.reloadData()
            }
            
            APPTransactionPair.default.selectPairModel = model
            self?.viewModel.currentPairModel = APPTransactionPair.default.selectPairModel
            self?.viewModel.currentOder = CoinOrderModel()
            self?.viewModel.checkUpdateModel()
            //刷新最新成交价格
            self?.changePrice()
            //订阅深度
            self?.viewModel.isRefreshDepth = true
            self?.viewModel.changePair = true
            self?.viewModel.digit = String(format: "%d", (self?.viewModel.regularModel.priceDigit)!)
            self?.currencyView.digitBtn.nameLabel.text = kText("小数位数") + (self?.viewModel.digit)!
            //刷新资产
            self?.viewModel.assetBool = true
            
            self?.changeLeftName()
            
        }
        sideslipView?.closelipBlock = {[weak self] in
            self?.viewModel.isRefreshPair = true
        }
    }
    
    func archiveOrderDepth() {
        ServiceSocketManager.shared.isLeave = false
        let tickServer = ServerOrderDepth()
        ServiceSocketManager.shared.delegate = self
        ServiceSocketManager.shared.subscribe(server: tickServer)
    }
    
    
    ///Mark -- SocketManagerDelegate
    func socket(didReadDepth data: [String : Any]) {
        viewModel.changeDepth(data: data)
    }
    func socket(didReadTick data: [String:Any]) {
        APPTransactionPair.default.updateParameters(data:data)
        self.changePrice()
    }
    func changePrice() {
        currencyView.changeCurrentPrice()
        if sideslipView != nil {
            if sideslipView?.isHidden == false {
                sideslipView?.tableView.reloadData()
            }
        }
    }
    
    func clearDepth()  {
        self.viewModel.depModel?.depUpArr.removeAll()
        self.viewModel.depModel?.deptDownArr.removeAll()
        currencyView.tableView.reloadData()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @objc func goKline() {
        let model = viewModel.currentPairModel
        let vc = KlineViewController()
        vc.viewModel.coinModel = model
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

extension CurrencyExchangeViewController:TransactionPairDelegate{
    func requestSuccess() {
        viewModel.currentPairModel = APPTransactionPair.default.selectPairModel
        if sideslipView != nil {
            if sideslipView?.isHidden == false {
                sideslipView?.updateHeadInformation()
                self.viewModel.selectPairName = (sideslipView?.selectName)!
                sideslipView?.currentPairModel = viewModel.currentPairModel
                sideslipView?.startSubscription()
            }
        }
    
        viewModel.isRefreshPair = true
        viewModel.isRefreshDepth = true
        self.changeLeftName()
        self.viewModel.currentOder = CoinOrderModel()
        viewModel.checkUpdateModel()
        self.viewModel.changePair = true
        self.viewModel.digit = String(format: "%d", self.viewModel.regularModel.priceDigit)
        currencyView.digitBtn.nameLabel.text = kText("小数位数") + viewModel.digit!
        currencyView.digitBtn.isHidden = false
        viewModel.assetBool = true
    }

}
extension CurrencyExchangeViewController: ServiceSocketDelegate {
    func orderDepth(didRead data: [String : Any]) {
        viewModel.changeOrderData(data: data)
    }
    
    func changeOrderStates() {
        self.viewModel.coinOrderArr = []
        self.viewModel.currentOder = CoinOrderModel()
        self.viewModel.coinOrder = true
        self.archiveOrderDepth()
    }
    
    func closeSocket()  {
        viewModel.currentOder = CoinOrderModel()
        viewModel.coinOrderArr.removeAll()
        currencyView.entrustTableView.reloadData()
    }
    
}
